<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import { Head, Link, useForm, router } from '@inertiajs/vue3';
import { computed } from 'vue';

const props = defineProps({
    notifications: Object,
    unreadCount: Number,
});

const formatTime = (time) => {
    if (!time) return '';
    const date = new Date(time);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
    });
};

const getUserAvatar = (avatar, name) => {
    if (avatar) {
        return avatar.startsWith('http') ? avatar : `/storage/${avatar}`;
    }
    return `https://api.dicebear.com/7.x/avataaars/svg?seed=${name || 'user'}`;
};

const markAllAsReadForm = useForm({});

const markAllAsRead = () => {
    markAllAsReadForm.post(route('notifications.markAllAsRead'), {
        preserveScroll: true,
        onSuccess: () => {
            router.reload({ only: ['notifications', 'unreadCount'] });
        },
    });
};

const markAsRead = (notificationId) => {
    if (props.notifications.data.find(n => n.id === notificationId && n.read_at)) {
        return; // 已经已读，不需要再次标记
    }
    
    router.post(route('notifications.markAsRead', notificationId), {}, {
        preserveScroll: true,
        onSuccess: () => {
            router.reload({ only: ['notifications', 'unreadCount'] });
        },
    });
};

const getNotificationUrl = (notification) => {
    const data = notification.data;
    if (data.post_slug) {
        return route('posts.show', data.post_slug);
    }
    return route('notifications.index');
};

const getNotificationText = (notification) => {
    const data = notification.data;
    if (notification.type === 'App\\Notifications\\PostReplied') {
        if (data.parent_reply_id) {
            return `${data.replier_name} 回复了你的评论`;
        } else {
            return `${data.replier_name} 回复了你的帖子《${data.post_title}》`;
        }
    }
    return '你有新通知';
};
</script>

<template>
    <Head title="通知中心" />

    <AuthenticatedLayout>
        <div class="space-y-6">
            <!-- 标题和操作 -->
            <div class="flex items-center justify-between">
                <h1 class="text-2xl font-bold">通知中心</h1>
                <div class="flex items-center gap-3">
                    <span class="text-sm text-muted-foreground">
                        未读：{{ unreadCount }} 条
                    </span>
                    <PrimaryButton
                        v-if="unreadCount > 0"
                        @click="markAllAsRead"
                        :disabled="markAllAsReadForm.processing"
                        class="h-9"
                    >
                        全部标记为已读
                    </PrimaryButton>
                </div>
            </div>

            <!-- 通知列表 -->
            <div class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                <div class="px-6">
                    <div v-if="notifications.data && notifications.data.length > 0" class="space-y-4">
                        <div
                            v-for="notification in notifications.data"
                            :key="notification.id"
                            @click="markAsRead(notification.id)"
                            :class="[
                                'p-4 border rounded-lg cursor-pointer transition-colors',
                                notification.read_at ? 'bg-card hover:bg-muted/50' : 'bg-primary/5 border-primary/20 hover:bg-primary/10'
                            ]"
                        >
                            <div class="flex gap-4">
                                <img
                                    :src="getUserAvatar(notification.data.replier_avatar, notification.data.replier_name)"
                                    :alt="notification.data.replier_name"
                                    class="w-10 h-10 rounded-full flex-shrink-0"
                                />
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-start justify-between gap-2">
                                        <div class="flex-1">
                                            <Link
                                                :href="getNotificationUrl(notification)"
                                                class="block hover:opacity-80 transition-opacity"
                                            >
                                                <p class="text-sm font-medium text-foreground">
                                                    {{ getNotificationText(notification) }}
                                                </p>
                                                <p v-if="notification.data.reply_content" class="text-sm text-muted-foreground mt-1 line-clamp-2">
                                                    {{ notification.data.reply_content }}
                                                </p>
                                                <div class="flex items-center gap-2 mt-2">
                                                    <span class="text-xs text-muted-foreground">
                                                        {{ formatTime(notification.created_at) }}
                                                    </span>
                                                    <Link
                                                        v-if="notification.data.bar_slug"
                                                        :href="route('bars.show', notification.data.bar_slug)"
                                                        @click.stop
                                                        class="text-xs text-primary hover:underline"
                                                    >
                                                        {{ notification.data.bar_name }}
                                                    </Link>
                                                </div>
                                            </Link>
                                        </div>
                                        <div v-if="!notification.read_at" class="w-2 h-2 rounded-full bg-primary flex-shrink-0 mt-1"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 空状态 -->
                    <div v-else class="text-center py-12 text-muted-foreground">
                        <p>暂无通知</p>
                    </div>

                    <!-- 分页 -->
                    <div v-if="notifications.links && notifications.links.length > 3" class="flex items-center justify-center gap-2 pt-6">
                        <Link
                            v-for="(link, index) in notifications.links"
                            :key="index"
                            :href="link.url || '#'"
                            v-html="link.label"
                            :class="[
                                'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-all h-9 px-3 py-2',
                                link.active ? 'bg-primary text-primary-foreground shadow-sm' : 'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
                                !link.url ? 'text-muted-foreground cursor-not-allowed opacity-50' : ''
                            ]"
                        />
                    </div>
                </div>
            </div>
        </div>
    </AuthenticatedLayout>
</template>

